<?php
/**
 * User: xuhong
 * Date: 2018/10/30
 */

namespace extend\wechat\mp;

class Auth
{
    /**
     * 获取网页授权code
     * @param $redirect_uri
     * @param string $appid
     * @param string $auth_type
     * @param string $param
     */
    public static function webAuthUrl($redirect_uri, $appid, $auth_type = "snsapi_base", $param = "")
    {
        // 跳转地址
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$auth_type}&state={$param}&connect_redirect=1#wechat_redirect";

        Header("Location:{$url}");
        exit;
    }

    /**
     * 获取网页授权凭证
     * @param $auth_code
     * @param string $appid
     * @param string $appsecret
     * @return mixed
     */
    public static function webAccessToken($auth_code, $appid, $appsecret)
    {
        // 获取授权信息
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$auth_code}&grant_type=authorization_code";

        return getRequest($url);
    }

    /**
     * 获取用户信息
     * @param $access_token
     * @param $openid
     * @return mixed
     */
    public static function webUserInfo($access_token, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";

        return getRequest($url);
    }


    /**
     * 刷新 access_token
     * @param $refresh_token
     * @param $appid
     * @return mixed
     */
    public static function webRefreshToken($refresh_token, $appid)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$appid}&grant_type=refresh_token&refresh_token={$refresh_token}";

        return getRequest($url);
    }


    /**
     * 检测 web_access_token 是否有效
     * @param $access_token
     * @param $openid
     * @return mixed
     */
    public static function checkAccessToken($access_token, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/auth?access_token={$access_token}&openid={$openid}";

        return getRequest($url);
    }
}